import time
from django.utils.deprecation import MiddlewareMixin
import logging

logger = logging.getLogger(__name__)


class RequestTimeMiddleware(MiddlewareMixin):
    """Middleware to log request processing time"""

    def process_request(self, request):
        request.start_time = time.time()
        return None

    def process_response(self, request, response):
        if not hasattr(request, 'start_time'):
            return response

        total_time = time.time() - request.start_time
        milliseconds = int(total_time * 1000)

        logger.info(
            f"method={request.method} path={request.path} "
            f"status={response.status_code} duration={milliseconds}ms"
        )

        response['X-Request-Duration'] = f'{milliseconds}ms'
        return response